package com.huawang.mdesign.model.service.inter;

import com.huawang.business.command.CommandAddType;
import com.huawang.business.command.CommandParameter;
import com.huawang.business.constants.ErrorCode;
import com.huawang.business.constants.ModelActionName;
import com.huawang.business.constants.ModelConstantURI;
import com.huawang.business.constants.SystemConstants;
import com.huawang.business.dto.ActivityEdgeRoute;
import com.huawang.business.dto.AppendModelDTO;
import com.huawang.business.dto.ModelPropertyInfo;
import com.huawang.business.dto.UpdateModelDTO;
import com.huawang.business.exception.AbortExecutionException;
import com.huawang.business.service.model.base.UmlService;
import com.huawang.business.service.model.core.InternalItemFlowService;
import com.huawang.business.service.model.core.InternalUmlService;
import com.huawang.business.service.model.core.ModelPropertyInfoService;
import com.huawang.business.service.model.core.property.UpdateModelFactory;
import com.huawang.business.service.transaction.TransactionServiceImpl;
import com.huawang.business.util.InstanceVoUtils;
import com.huawang.business.vo.ItemFlowEndListVo;
import com.huawang.business.vo.ModelResultVo;
import com.huawang.core.definition.mof.UMLDefinitionConstants;
import com.huawang.core.definition.mof.cmof.reflection.impl.BasicRElement;
import com.huawang.core.definition.mof.instances.MetaClassInstance;
import com.huawang.core.semantics.entity.queryResult.MofResultContainer;
import com.huawang.core.semantics.entity.queryResult.QueryPropertyForm;
import com.huawang.core.semantics.entity.transaction.LocalTransaction;
import com.huawang.core.semantics.exception.LocalTransactionNotStartException;
import com.huawang.core.semantics.exception.TransactionNotExistingException;
import com.huawang.core.semantics.service.query.QueryPropertyService;
import com.huawang.mdesign.model.service.dto.*;
import com.huawang.mdesign.model.service.util.LogUtil;
import com.huawang.mdesign.model.service.vo.*;
import com.huawang.mdesign.model.service.vo.selectelementitem.SelectElementItem;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.BooleanUtils;
import org.apache.commons.lang3.StringUtils;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import static com.huawang.business.constants.ModelActionName.*;

/**
 * @author baibf
 * @description 项流Service
 * @date 2022/8/9 16:21
 **/
@Service
@Primary
@Slf4j
public class ItemFlowService {

    public static final String CURRENT = "current";
    public static final String GENERAL = "general";
    public static final String AGGREGATION = "aggregation";
    @Autowired
    private UmlService umlService;

    @Autowired
    private InternalUmlService internalUmlService;

    @Autowired
    private ModelPropertyInfoService modelPropertyInfoService;

    @Autowired
    private InternalItemFlowService internalItemFlowService;

    @Autowired
    private TransactionServiceImpl transactionService;

    @Autowired
    private QueryPropertyService queryPropertyService;

    @NotNull
    public ModelResultVo createItemFlow(CreateItemFlowDTO createItemFlowDto) {
        LogUtil.printSerializeOnlineLogs("createItemFlowDto: ", createItemFlowDto);
        final String projectId = createItemFlowDto.getProjectId();
        ModelResultVo modelResultVo = new ModelResultVo();

        LocalTransaction transaction = transactionService.createTransaction(projectId, ADD_MODEL);
        String defaultName = null;
        if (CollectionUtils.isNotEmpty(createItemFlowDto.getConveyedItems())) {
            MetaClassInstance conveyed = internalUmlService.fetchInstance(createItemFlowDto.getConveyedItems().get(0), projectId);
            defaultName = "流" + internalUmlService.queryStringProperty(projectId, conveyed,
                    UMLDefinitionConstants.NamedElement_name);
        }
        final List<String> appliedStereotype = new ArrayList<>();
        // 应用构造型非null且size>0，使用传入的构造型
        if (CollectionUtils.isNotEmpty(createItemFlowDto.getApplyStereotypes())) {
            appliedStereotype.add(createItemFlowDto.getApplyStereotypes().get(0));
        } else {
            appliedStereotype.add(UMLDefinitionConstants.SysML_ItemFlow);
        }
        String parentId = createItemFlowDto.getParentId();
        MetaClassInstance parent = internalUmlService.fetchInstance(parentId, projectId);
        if (Objects.nonNull(parent)) {
            Set<String> givenTypes = internalUmlService.getGivenTypes(projectId, parent);
            if (givenTypes.contains(UMLDefinitionConstants.SysMLInternalBlockDiagram)
                    || givenTypes.contains(UMLDefinitionConstants.SysMLActivityDiagram)
                    || givenTypes.contains(UMLDefinitionConstants.SysMLInteractionDiagram)) {
                MetaClassInstance context = internalUmlService.queryInstanceProperty(projectId, parent,
                        UMLDefinitionConstants.Diagram_context);
                if (Objects.isNull(context)) {
                    parent = internalUmlService.queryInstanceProperty(projectId, parent, UMLDefinitionConstants.Element_owner);
                } else {
                    parent = context;
                }
            } else {
                parent = internalUmlService.queryInstanceProperty(projectId, parent, UMLDefinitionConstants.Element_owner);
            }
            parentId = umlService.fetchOwningPackage(projectId, parent).getId();
        }

        try {
            // 创建ItemFlow
            CommandParameter parameter = CommandParameter.builder()
                    .type(CommandAddType.initCommitStatus(1))
                    .typeId(UMLDefinitionConstants.InformationFlow)
                    .projectId(projectId)
                    .instanceId(ModelConstantURI.initInstanceId())
                    .source(createItemFlowDto.getSource())
                    .target(createItemFlowDto.getTarget())
                    .parentId(parentId)
                    .defaultName(defaultName)
                    .applyStereotypes(appliedStereotype)
                    .build();
            MetaClassInstance result = umlService.addModel(parameter);
            List<MetaClassInstance> relatedActivityEdgeList = itemFlowSetProperties(createItemFlowDto, result, true);
            transactionService.commit(projectId);
            modelResultVo.setInstanceId(result.getId());
            InstanceVoUtils.fillModelResultVo(modelResultVo, transaction);
            if (StringUtils.isNotEmpty(createItemFlowDto.getInstanceId())) {
                modelResultVo.getModifyModel().add(createItemFlowDto.getInstanceId());
            }
            modelResultVo.getModifyModel().addAll(relatedActivityEdgeList.stream().map(BasicRElement::getId).collect(Collectors.toList()));

        } catch (TransactionNotExistingException | LocalTransactionNotStartException e) {
            throw AbortExecutionException.build(ErrorCode.TRANSACTION_ERROR, e);
        } catch (Exception e) {
            transactionService.rollBack(projectId, transaction);
            throw AbortExecutionException.build(ErrorCode.ADD_MODEL_ERROR, e);
        }

        return modelResultVo;
    }

    /**
     * description:设置项流的相关属性
     *
     * @return java.util.List<com.huawang.core.definition.mof.instances.MetaClassInstance>:返回mof无法计算但需要前端刷新的模型id
     * @author lx
     * @date 2024/3/18
     */
    @NotNull
    private List<MetaClassInstance> itemFlowSetProperties(@NotNull CreateItemFlowDTO itemFlowDto,
                                                          @NotNull MetaClassInstance itemFlow,
                                                          boolean isCreateItemFlow) {
        LogUtil.printSerializeOnlineLogs("itemFlowDto: {}, itemFlow: {}, isCreateItemFlow: {}", itemFlowDto,
                itemFlow, isCreateItemFlow);
        final String projectId = itemFlowDto.getProjectId();
        final String placeModelId = itemFlowDto.getInstanceId();
        final List<String> conveyedItems = itemFlowDto.getConveyedItems();
        final String itemPropertyId = itemFlowDto.getItemProperty();
        final String sourceId = itemFlowDto.getSource();
        final String targetId = itemFlowDto.getTarget();
        final Map<String, MetaClassInstance> instanceMap = internalUmlService.fetchInstances(
                Stream.concat(Stream.of(placeModelId, itemPropertyId, sourceId, targetId), conveyedItems.stream())
                        .collect(Collectors.toList()), projectId);

        List<UpdateModelDTO> updateModelDtos = new ArrayList<>();

        // fromToActivityGroup拆解:1.设置fromActivity和toActivity属性(需要去重添加) 2.设置SysML_ItemFlow_activities属性(保存group的关系)
        List<FromToActivityGroup> fromToActivityGroupList = itemFlowDto.getFromToActivityGroup();
        updateActivityGroupProperty(projectId, itemFlow, fromToActivityGroupList, isCreateItemFlow);

        // 添加传递对象
        List<MetaClassInstance> conveyedItemInstances = conveyedItems.stream().map(instanceMap::get).collect(Collectors.toList());
        updateModelDtos.add(UpdateModelFactory.newInstance(projectId, itemFlow.getId(), UMLDefinitionConstants.InformationFlow_conveyed, conveyedItemInstances));

        // 添加项属性
        MetaClassInstance itemPropertyInstance = instanceMap.get(itemPropertyId);
        updateModelDtos.add(UpdateModelFactory.newInstance(projectId, itemFlow.getId(), UMLDefinitionConstants.SysML_ItemFlow_itemProperty, itemPropertyInstance));

        // 添加信息源信息目标
        MetaClassInstance source = instanceMap.get(sourceId);
        MetaClassInstance target = instanceMap.get(targetId);
        updateModelDtos.add(UpdateModelFactory.newInstance(projectId, itemFlow.getId(), UMLDefinitionConstants.InformationFlow_informationSource, source));
        updateModelDtos.add(UpdateModelFactory.newInstance(projectId, itemFlow.getId(), UMLDefinitionConstants.InformationFlow_informationTarget, target));

        final MetaClassInstance placeInstance = instanceMap.get(placeModelId);
        if (Objects.isNull(placeInstance)) {
            log.info("项流无承载模型或承载模型查找失败, id:{}", itemFlowDto.getInstanceId());
            umlService.updateModelByBatch(updateModelDtos);
            return Collections.emptyList();
        }
        // 更新项流的实现边属性:
        // 1.承载模型为connector->InformationFlow_realizingConnector
        // 2.承载模型为activityEdge->InformationFlow_realizingActivityEdge
        // 3.承载模型为message->InformationFlow_realizingMessage
        // 4.承载模型为association->InformationFlow_realization
        Set<String> givenTypes = internalUmlService.getGivenTypes(projectId, placeInstance);
        Set<MetaClassInstance> relationShipSet = Stream.of(placeInstance).collect(Collectors.toSet());
        List<MetaClassInstance> relatedActivityEdgeList = new ArrayList<>();
        String correspondingProperty;
        if (givenTypes.contains(UMLDefinitionConstants.Connector)) {
            correspondingProperty = UMLDefinitionConstants.InformationFlow_realizingConnector;
        } else if (givenTypes.contains(UMLDefinitionConstants.ActivityEdge)) {
            correspondingProperty = UMLDefinitionConstants.InformationFlow_realizingActivityEdge;
            // 如果是创建项流，则需要额外将行为与当前边连接的路径加入项流的实现活动边属性中
            relatedActivityEdgeList = internalUmlService.fetchInstanceByIds(
                    findAllRealizing(projectId, placeModelId, sourceId, targetId), projectId);
            relationShipSet.addAll(relatedActivityEdgeList);
        } else if (givenTypes.contains(UMLDefinitionConstants.Message)) {
            correspondingProperty = UMLDefinitionConstants.InformationFlow_realizingMessage;
        } else {
            correspondingProperty = UMLDefinitionConstants.InformationFlow_realization;
        }
        List<String> unrealizedRelationship = queryPropertyService.getPropertyValueExist(projectId, itemFlow.getId(),
                correspondingProperty, new ArrayList<>(relationShipSet))
                .getNotExistValues().stream().map(Object::toString).collect(Collectors.toList());
        if (CollectionUtils.isNotEmpty(unrealizedRelationship)) {
            umlService.appendMultipleModel(projectId, itemFlow.getId(), correspondingProperty,
                    new ArrayList<>(internalUmlService.fetchInstanceByIds(unrealizedRelationship, projectId)));
        }

        // 批量更新属性值
        umlService.updateModelByBatch(updateModelDtos);
        return relatedActivityEdgeList;
    }

    /**
     * description:通过项流编辑弹窗设置项流的活动组属性时的连带逻辑
     *
     * @param projectId
     * @param itemFlow
     * @param fromToActivityGroups:来源/到达活动组
     * @param isCreateItemFlow:是否为创建项流逻辑
     * @return void
     * @author lx
     * @date 2024/3/20
     */
    private void updateActivityGroupProperty(@NotNull String projectId,
                                             @NotNull MetaClassInstance itemFlow,
                                             @NotNull List<FromToActivityGroup> fromToActivityGroups,
                                             boolean isCreateItemFlow) {
        LogUtil.printSerializeOnlineLogs("projectId: {}, itemFlow: {}, fromToActivityGroups: {}, isCreateItemFlow: {}",
                projectId, itemFlow, fromToActivityGroups, isCreateItemFlow);
        if (CollectionUtils.isEmpty(fromToActivityGroups)) {
            log.info("更新时来源/到达活动组为空");
            return;
        }
        // 如果是创建项流，则取第一个来源/到达活动组添加，否则则全部添加
        if (isCreateItemFlow) {
            fromToActivityGroups = Collections.singletonList(fromToActivityGroups.get(0));
        }

        List<String> unFromActivity = queryPropertyService.getPropertyValueExist(projectId, itemFlow.getId(),
                UMLDefinitionConstants.SysML_ItemFlow_fromActivity,
                fromToActivityGroups.stream().map(FromToActivityGroup::getFromActivity).collect(Collectors.toList()))
                .getNotExistValues().stream().map(Object::toString).collect(Collectors.toList());

        List<String> unToActivity = queryPropertyService.getPropertyValueExist(projectId, itemFlow.getId(),
                UMLDefinitionConstants.SysML_ItemFlow_toActivity,
                fromToActivityGroups.stream().map(FromToActivityGroup::getToActivity).collect(Collectors.toList()))
                .getNotExistValues().stream().map(Object::toString).collect(Collectors.toList());

        List<String> unActivities = queryPropertyService.getPropertyValueExist(projectId, itemFlow.getId(),
                UMLDefinitionConstants.SysML_ItemFlow_activities,
                fromToActivityGroups.stream().map(it -> it.getFromActivity() + SystemConstants.ITEM_FLOW_ACTIVITIES_SEPARATOR + it.getToActivity())
                        .collect(Collectors.toList()))
                .getNotExistValues().stream().map(Object::toString).collect(Collectors.toList());

        Map<String, MetaClassInstance> instanceMap = internalUmlService.fetchInstances(
                Stream.of(unFromActivity, unToActivity, unActivities).flatMap(Collection::stream).collect(Collectors.toList()), projectId);

        List<AppendModelDTO> appendModelDTOS = new ArrayList<>();
        appendModelDTOS.add(new AppendModelDTO(projectId, itemFlow.getId(), UMLDefinitionConstants.SysML_ItemFlow_fromActivity,
                unFromActivity.stream().map(instanceMap::get).collect(Collectors.toList())));
        appendModelDTOS.add(new AppendModelDTO(projectId, itemFlow.getId(), UMLDefinitionConstants.SysML_ItemFlow_toActivity,
                unToActivity.stream().map(instanceMap::get).collect(Collectors.toList())));
        appendModelDTOS.add(new AppendModelDTO(projectId, itemFlow.getId(), UMLDefinitionConstants.SysML_ItemFlow_activities,
                new ArrayList<>(unActivities)));
        umlService.appendModelByBatch(projectId, appendModelDTOS);
    }

    @NotNull
    private List<MetaClassInstance> singleUpdateActivityGroupProperty(@NotNull String projectId,
                                                                      @NotNull MetaClassInstance itemFlow,
                                                                      @NotNull List<FromToActivityGroup> fromToActivityGroups) {
        LogUtil.printSerializeOnlineLogs("projectId: {}, itemFlow: {}, fromToActivityGroups: {}", projectId,
                itemFlow, fromToActivityGroups);
        if (CollectionUtils.isEmpty(fromToActivityGroups)) {
            umlService.removeModel(projectId, itemFlow.getId(), UMLDefinitionConstants.SysML_ItemFlow_fromActivity);
            umlService.removeModel(projectId, itemFlow.getId(), UMLDefinitionConstants.SysML_ItemFlow_toActivity);
            umlService.removeModel(projectId, itemFlow.getId(), UMLDefinitionConstants.SysML_ItemFlow_activities);
            umlService.removeModel(projectId, itemFlow.getId(), UMLDefinitionConstants.InformationFlow_realizingActivityEdge);
        }

        List<MetaClassInstance> relatedInstances = new ArrayList<>();
        List<UpdateModelDTO> updateModelDTOS = new ArrayList<>();
        List<String> groupRelationIds = new ArrayList<>();
        List<String> fromActivityIds = new ArrayList<>();
        List<String> toActivityIds = new ArrayList<>();

        fromToActivityGroups.forEach(it -> {
            String relation = it.getFromActivity() + SystemConstants.ITEM_FLOW_ACTIVITIES_SEPARATOR + it.getToActivity();
            fromActivityIds.add(it.getFromActivity());
            toActivityIds.add(it.getToActivity());
            groupRelationIds.add(relation);
        });

        List<MetaClassInstance> fromActivityInstances = internalUmlService.fetchInstanceByIds(fromActivityIds, projectId);
        List<MetaClassInstance> toActivityInstances = internalUmlService.fetchInstanceByIds(toActivityIds, projectId);
        // 更新项流的来源、到达活动及活动组属性
        updateModelDTOS.add(UpdateModelFactory.newInstance(projectId, itemFlow.getId(), UMLDefinitionConstants.SysML_ItemFlow_fromActivity, fromActivityInstances));
        updateModelDTOS.add(UpdateModelFactory.newInstance(projectId, itemFlow.getId(), UMLDefinitionConstants.SysML_ItemFlow_toActivity, toActivityInstances));
        updateModelDTOS.add(UpdateModelFactory.newInstance(projectId, itemFlow.getId(), UMLDefinitionConstants.SysML_ItemFlow_activities, groupRelationIds));

        // 如果Activity没有对应的callBehaviorAction，创建callBehaviorAction和ControlFlow
        List<MetaClassInstance> fromAndToActivityList = Stream.concat(fromActivityInstances.stream(), toActivityInstances.stream()).collect(Collectors.toList());
        List<ModelPropertyInfo> fromAndToActivityModels = modelPropertyInfoService.createModelPropertyInfoList(projectId, fromAndToActivityList,
                Stream.of(UMLDefinitionConstants.A_behavior_callBehaviorAction_callBehaviorAction).collect(Collectors.toList()));
        Map<String, List<MetaClassInstance>> callBehaviorActionMap = fromAndToActivityModels.stream().collect(Collectors.toMap(
                ModelPropertyInfo::getInstanceId, fromAndToActivityModel ->
                        fromAndToActivityModel.queryListInstanceValue(UMLDefinitionConstants.A_behavior_callBehaviorAction_callBehaviorAction), (a, b) -> a));

        // 查询信息源信息目标
        MetaClassInstance source = internalUmlService.queryListInstanceProperty(projectId, itemFlow, UMLDefinitionConstants.InformationFlow_informationSource).get(0);
        MetaClassInstance target = internalUmlService.queryListInstanceProperty(projectId, itemFlow, UMLDefinitionConstants.InformationFlow_informationTarget).get(0);

        List<CommandParameter> commandParameters = new ArrayList<>();
        List<String> controlFlowIds = new ArrayList<>();
        Map<String, String> itemFlowWithControlFlowMap = new HashMap<>();
        groupRelationIds.forEach(it -> {
            String[] activities = it.split(SystemConstants.ITEM_FLOW_ACTIVITIES_SEPARATOR);
            String fromActivityId = activities[0];
            String toActivityId = activities[1];
            List<MetaClassInstance> fromCallBehaviorActionList = callBehaviorActionMap.get(fromActivityId);
            List<MetaClassInstance> toCallBehaviorActionList = callBehaviorActionMap.get(toActivityId);
            // 如果来源活动的分配目标不包含信息源/到达活动不包含信息目标， 则将其设置为分配目标
            MetaClassInstance fromActivity = internalUmlService.fetchExistInstance(fromActivityId, projectId);
            MetaClassInstance toActivity = internalUmlService.fetchExistInstance(toActivityId, projectId);
            List<MetaClassInstance> fromAlloctedList = internalUmlService.queryListInstanceProperty(projectId, fromActivity, UMLDefinitionConstants.NamedElement_allocatedTo);
            List<MetaClassInstance> toAlloctedList = internalUmlService.queryListInstanceProperty(projectId, toActivity, UMLDefinitionConstants.NamedElement_allocatedTo);
            if (!fromAlloctedList.contains(source)) {
                umlService.appendModel(projectId, fromActivity.getId(), UMLDefinitionConstants.NamedElement_allocatedTo, source);
            }
            if (!toAlloctedList.contains(target)) {
                umlService.appendModel(projectId, toActivity.getId(), UMLDefinitionConstants.NamedElement_allocatedTo, target);
            }

            String controlFlowId;
            if (CollectionUtils.isNotEmpty(fromCallBehaviorActionList) && CollectionUtils.isNotEmpty(toCallBehaviorActionList)) {

                List<MetaClassInstance> activityEdgeList = internalItemFlowService.findActivityEdgeBetweenAction(projectId,
                        fromCallBehaviorActionList, toCallBehaviorActionList);
                if (CollectionUtils.isNotEmpty(activityEdgeList)) {
                    updateModelDTOS.add(UpdateModelFactory.newInstance(
                            projectId, itemFlow.getId(), UMLDefinitionConstants.InformationFlow_realizingActivityEdge, activityEdgeList));
                    relatedInstances.addAll(activityEdgeList);
                } else {
                    controlFlowId = ModelConstantURI.initInstanceId();
                    CommandParameter controlFlowParameter = CommandParameter.builder()
                            .projectId(projectId)
                            .typeId(UMLDefinitionConstants.ControlFlow)
                            .type(CommandAddType.RELATIONSHIP)
                            .parentId(fromActivityId)
                            .instanceId(controlFlowId)
                            .source(fromCallBehaviorActionList.get(0).getId())
                            .target(toCallBehaviorActionList.get(0).getId())
                            .build();
                    commandParameters.add(controlFlowParameter);
                    controlFlowIds.add(controlFlowId);
                    itemFlowWithControlFlowMap.put(itemFlow.getId(), controlFlowId);
                }
            } else {
                final String firstCallBehaviorActionId = ModelConstantURI.initInstanceId();
                CommandParameter firstCallBehaviorActionParameter = CommandParameter.builder()
                        .projectId(projectId)
                        .typeId(UMLDefinitionConstants.CallBehaviorAction)
                        .type(CommandAddType.MODEL)
                        .parentId(fromActivityId)
                        .instanceId(firstCallBehaviorActionId)
                        .build();
                umlService.addModel(firstCallBehaviorActionParameter);
                updateModelDTOS.add(UpdateModelFactory.newInstance(projectId, firstCallBehaviorActionId,
                        UMLDefinitionConstants.CallBehaviorAction_behavior,
                        internalUmlService.fetchInstance(fromActivityId, projectId)));

                String secondCallBehaviorActionId = ModelConstantURI.initInstanceId();
                CommandParameter secondCallBehaviorActionParameter = CommandParameter.builder()
                        .projectId(projectId)
                        .typeId(UMLDefinitionConstants.CallBehaviorAction)
                        .type(CommandAddType.MODEL)
                        .parentId(fromActivityId)
                        .instanceId(secondCallBehaviorActionId)
                        .build();
                umlService.addModel(secondCallBehaviorActionParameter);
                updateModelDTOS.add(UpdateModelFactory.newInstance(projectId, secondCallBehaviorActionId,
                        UMLDefinitionConstants.CallBehaviorAction_behavior,
                        internalUmlService.fetchInstance(toActivityId, projectId)));

                controlFlowId = ModelConstantURI.initInstanceId();
                CommandParameter controlFlowParameter = CommandParameter.builder()
                        .projectId(projectId)
                        .typeId(UMLDefinitionConstants.ControlFlow)
                        .type(CommandAddType.RELATIONSHIP)
                        .parentId(fromActivityId)
                        .instanceId(controlFlowId)
                        .source(firstCallBehaviorActionId)
                        .target(secondCallBehaviorActionId)
                        .build();
                commandParameters.add(controlFlowParameter);
                controlFlowIds.add(controlFlowId);
                itemFlowWithControlFlowMap.put(itemFlow.getId(), controlFlowId);
            }
        });

        if (CollectionUtils.isNotEmpty(commandParameters)) {
            final List<MetaClassInstance> instanceList = umlService.addModelByBatch(commandParameters);
            final Map<String, MetaClassInstance> instanceMap = instanceList.stream().collect(Collectors.toMap(BasicRElement::getId, b -> b, (k, v) -> k));
            itemFlowWithControlFlowMap.forEach((k, v) ->
                    updateModelDTOS.add(UpdateModelFactory.newInstance(projectId, k,
                            UMLDefinitionConstants.InformationFlow_realizingActivityEdge,
                            Collections.singletonList(instanceMap.get(v))))
            );
            controlFlowIds.forEach(controlFlowId -> relatedInstances.add(instanceMap.get(controlFlowId)));
        }

        if (CollectionUtils.isNotEmpty(updateModelDTOS)) {
            umlService.updateModelByBatch(updateModelDTOS);
        }
        return relatedInstances;
    }

    @NotNull
    public List<String> findAllRealizing(@NotNull String projectId,
                                         @NotNull String instanceId,
                                         @NotNull String sourceId,
                                         @NotNull String targetId) {
        LogUtil.printOnlineLogs("projectId: {}, instanceId: {}, sourceId: {}, targetId: {}", projectId, instanceId, sourceId,
                targetId);
        MetaClassInstance source = internalUmlService.fetchInstance(sourceId, projectId);
        MetaClassInstance target = internalUmlService.fetchInstance(targetId, projectId);
        // 活动图新增规则:1.原有逻辑
        MofResultContainer endsContainer = internalUmlService.queryProperty(projectId, internalUmlService.getQueryPropertyForm(
                Stream.of(source, target).collect(Collectors.toList()),
                Stream.of(UMLDefinitionConstants.A_allocatedTo_namedElement_namedElement,
                        UMLDefinitionConstants.A_type_typedElement_typedElement).collect(Collectors.toList())));

        List<MetaClassInstance> sourceToBehavior = endsContainer.queryListInstanceProperty(
                sourceId, UMLDefinitionConstants.A_allocatedTo_namedElement_namedElement);
        List<MetaClassInstance> targetToBehavior = endsContainer.queryListInstanceProperty(
                targetId, UMLDefinitionConstants.A_allocatedTo_namedElement_namedElement);

        List<MetaClassInstance> sourceProperty = endsContainer.queryListInstanceProperty(
                sourceId, UMLDefinitionConstants.A_type_typedElement_typedElement).stream().filter(it ->
                internalUmlService.checkInstanceType(projectId, it, UMLDefinitionConstants.Property)).collect(Collectors.toList());
        List<MetaClassInstance> targetProperty = endsContainer.queryListInstanceProperty(
                targetId, UMLDefinitionConstants.A_type_typedElement_typedElement).stream().filter(it ->
                internalUmlService.checkInstanceType(projectId, it, UMLDefinitionConstants.Property)).collect(Collectors.toList());

        MofResultContainer propertyContainer = internalUmlService.queryProperty(projectId, internalUmlService.getQueryPropertyForm(
                Stream.of(sourceProperty, targetProperty).flatMap(Collection::stream).collect(Collectors.toList()),
                Stream.of(UMLDefinitionConstants.A_allocatedTo_namedElement_namedElement).collect(Collectors.toList())));

        MofResultContainer behaviorContainer = internalUmlService.queryProperty(projectId, internalUmlService.getQueryPropertyForm(
                Stream.of(sourceToBehavior, targetToBehavior).flatMap(Collection::stream).collect(Collectors.toList()),
                Stream.of(UMLDefinitionConstants.A_behavior_callBehaviorAction_callBehaviorAction).collect(Collectors.toList())));

        List<MetaClassInstance> sourceCallBehaviorAction = new ArrayList<>();
        List<MetaClassInstance> targetCallBehaviorAction = new ArrayList<>();
        sourceCallBehaviorAction.addAll(sourceProperty.stream()
                .flatMap(it -> propertyContainer.queryListInstanceProperty(it.getId(), UMLDefinitionConstants.A_allocatedTo_namedElement_namedElement).stream())
                .filter(it -> internalUmlService.checkInstanceType(projectId, it, UMLDefinitionConstants.CallBehaviorAction))
                .collect(Collectors.toList()));

        sourceCallBehaviorAction.addAll(sourceToBehavior.stream()
                .flatMap(it -> behaviorContainer.queryListInstanceProperty(it.getId(), UMLDefinitionConstants.A_behavior_callBehaviorAction_callBehaviorAction).stream())
                .collect(Collectors.toList()));

        targetCallBehaviorAction.addAll(targetProperty.stream()
                .flatMap(it -> propertyContainer.queryListInstanceProperty(it.getId(), UMLDefinitionConstants.A_allocatedTo_namedElement_namedElement).stream())
                .filter(it -> internalUmlService.checkInstanceType(projectId, it, UMLDefinitionConstants.CallBehaviorAction))
                .collect(Collectors.toList()));

        targetCallBehaviorAction.addAll(targetToBehavior.stream()
                .flatMap(it -> behaviorContainer.queryListInstanceProperty(it.getId(), UMLDefinitionConstants.A_behavior_callBehaviorAction_callBehaviorAction).stream())
                .collect(Collectors.toList()));

        if (CollectionUtils.isEmpty(sourceCallBehaviorAction) || CollectionUtils.isEmpty(targetCallBehaviorAction)) {
            log.info("未找到来源端调用动作行为或到达端调用动作行为");
            return Collections.emptyList();
        }
        return findAllRealizingByAction(projectId, sourceCallBehaviorAction, targetCallBehaviorAction, instanceId);
    }

    @NotNull
    public List<String> findAllRealizingByAction(@NotNull String projectId,
                                                 @NotNull List<MetaClassInstance> sourceCallBehaviorActionList,
                                                 @NotNull List<MetaClassInstance> targetCallBehaviorActionList,
                                                 @NotNull String instanceId) {
        LogUtil.printSerializeOnlineLogs("projectId: {}, sourceCallBehaviorActionList: {}, targetCallBehaviorActionList: {}, instanceId: {}",
                projectId, sourceCallBehaviorActionList, targetCallBehaviorActionList, instanceId);
        List<String> allRealizingList = new ArrayList<>();
        List<ActivityEdgeRoute> sourceActivityEdgeRoute = new ArrayList<>();
        List<ActivityEdgeRoute> targetActivityEdgeRoute = new ArrayList<>();
        List<MetaClassInstance> sourceVisitList = new ArrayList<>();
        List<MetaClassInstance> targetVisitList = new ArrayList<>();
        List<MetaClassInstance> tempNodeList = new ArrayList<>();
        // 如果存在栓一定绑定在调用行为上，反向直接查找：如果存在栓，则连接边的为栓;不存在栓，则连接边的为调用行为
        // 同时将这些节点作为寻找链路上的头节点，循环遍历所有节点
        sourceCallBehaviorActionList.forEach(it -> {
            List<MetaClassInstance> sourcePin = internalUmlService.queryListInstanceProperty(projectId, it, UMLDefinitionConstants.Action_output);
            if (!sourcePin.isEmpty()) {
                sourcePin.forEach(entry -> sourceActivityEdgeRoute.add(new ActivityEdgeRoute(new ArrayList<>(), entry.getId())));
                sourceVisitList.addAll(sourcePin);
            } else {
                sourceActivityEdgeRoute.add(new ActivityEdgeRoute(new ArrayList<>(), it.getId()));
                sourceVisitList.add(it);
            }
        });
        targetCallBehaviorActionList.forEach(it -> {
            List<MetaClassInstance> targetPin = internalUmlService.queryListInstanceProperty(projectId, it, UMLDefinitionConstants.Action_input);
            if (!targetPin.isEmpty()) {
                targetPin.forEach(entry -> targetActivityEdgeRoute.add(new ActivityEdgeRoute(new ArrayList<>(), entry.getId())));
                targetVisitList.addAll(targetPin);
            } else {
                targetActivityEdgeRoute.add(new ActivityEdgeRoute(new ArrayList<>(), it.getId()));
                targetVisitList.add(it);
            }
        });

        List<List<String>> sourceEdge = querySourceEdge(projectId, instanceId, sourceActivityEdgeRoute, sourceVisitList, tempNodeList);
        List<List<String>> targetEdge = queryTargetEdge(projectId, instanceId, targetActivityEdgeRoute, targetVisitList, tempNodeList);
        sourceEdge.forEach(allRealizingList::addAll);
        targetEdge.forEach(allRealizingList::addAll);
        return allRealizingList.stream().distinct().collect(Collectors.toList());
    }

    @NotNull
    private List<List<String>> queryTargetEdge(@NotNull String projectId, @NotNull String instanceId, List<ActivityEdgeRoute> targetActivityEdgeRoute, List<MetaClassInstance> targetVisitList, List<MetaClassInstance> tempNodeList) {
        LogUtil.printSerializeOnlineLogs("projectId: {}, instanceId: {}, targetActivityEdgeRoute: {}, targetVisitList: {}, tempNodeList: {}",
                projectId, instanceId, targetActivityEdgeRoute, targetVisitList, tempNodeList);
        List<List<String>> targetEdge = new ArrayList<>();
        List<String> targetVisitedList = new ArrayList<>();
        while (!targetVisitList.isEmpty()) {
            tempNodeList.clear();
            tempNodeList.addAll(targetVisitList.stream().distinct().collect(Collectors.toList()));
            targetVisitList.clear();
            targetVisitList.addAll(tempNodeList);
            for (MetaClassInstance node : tempNodeList) {
                // 查询连接边，temp存放该节点下一连接边信息
                List<MetaClassInstance> tempEdgeList = internalUmlService.queryListInstanceProperty(projectId, node, UMLDefinitionConstants.ActivityNode_incoming);
                // 如果没有连接边，走到死路，直接remove掉末节点为node的所有路径
                if (tempEdgeList.isEmpty()) {
                    targetActivityEdgeRoute.removeIf(it -> it.getLastNode().equals(node.getId()));
                    targetVisitList.remove(node);
                    continue;
                }
                // 存在连接边，获取连接边末节点为node的所有路径
                // 连接边等于中间边, 添加路径;否，将temp追加至末节点为node的List<Edge>中，再清空所有末节点为node的路径
                tempEdgeList.forEach(it -> {
                    List<ActivityEdgeRoute> route = targetActivityEdgeRoute.stream().filter(entry ->
                            Objects.equals(entry.getLastNode(), node.getId())).collect(Collectors.toList());
                    if (it.getId().equals(instanceId)) {
                        targetEdge.addAll(route.stream().map(ActivityEdgeRoute::getRoutes).collect(Collectors.toList()));
                    } else {
                        // 追加temp边
                        route.forEach(entry -> {
                            List<String> tempRoute = new ArrayList<>(entry.getRoutes());
                            tempRoute.add(it.getId());
                            MetaClassInstance tempEdge = internalUmlService.fetchInstance(it.getId(), projectId);
                            MetaClassInstance nextNode = internalUmlService.queryInstanceProperty(
                                    projectId, tempEdge, UMLDefinitionConstants.ActivityEdge_source);
                            if (Objects.nonNull(nextNode) && BooleanUtils.isTrue(isValidNode(projectId, targetVisitedList, nextNode))) {
                                targetActivityEdgeRoute.add(new ActivityEdgeRoute(tempRoute, nextNode.getId()));
                                targetVisitList.add(nextNode);
                            }
                        });
                    }
                });
                targetActivityEdgeRoute.removeIf(it -> it.getLastNode().equals(node.getId()));
                targetVisitList.remove(node);
                // 该节点已访问过，下次不再访问
                targetVisitedList.add(node.getId());
            }
        }
        return targetEdge;
    }

    @NotNull
    private List<List<String>> querySourceEdge(@NotNull String projectId, @NotNull String instanceId, List<ActivityEdgeRoute> sourceActivityEdgeRoute, List<MetaClassInstance> sourceVisitList, List<MetaClassInstance> tempNodeList) {
        LogUtil.printSerializeOnlineLogs("projectId: {}, instanceId: {}, sourceActivityEdgeRoute: {}, sourceVisitList: {}, tempNodeList: {}",
                projectId, instanceId, sourceActivityEdgeRoute, sourceVisitList, tempNodeList);
        List<List<String>> sourceEdge = new ArrayList<>();
        // 已被访问过的节点，访问过则不再追加访问
        List<String> sourceVisitedList = new ArrayList<>();
        while (!sourceVisitList.isEmpty()) {
            tempNodeList.clear();
            tempNodeList.addAll(sourceVisitList.stream().distinct().collect(Collectors.toList()));
            sourceVisitList.clear();
            sourceVisitList.addAll(tempNodeList);
            for (MetaClassInstance node : tempNodeList) {
                // 查询连接边，temp存放该节点下一连接边信息
                List<MetaClassInstance> tempEdgeList = internalUmlService.queryListInstanceProperty(projectId, node, UMLDefinitionConstants.ActivityNode_outgoing);
                // 如果没有连接边，走到死路，直接remove掉末节点为node的所有路径
                if (tempEdgeList.isEmpty()) {
                    sourceActivityEdgeRoute.removeIf(it -> it.getLastNode().equals(node.getId()));
                    sourceVisitList.remove(node);
                    continue;
                }
                // 存在连接边，获取连接边末节点为node的所有路径
                // 连接边等于中间边, 添加路径;否，将temp追加至末节点为node的List<Edge>中，再清空所有末节点为node的路径
                tempEdgeList.forEach(it -> {
                    List<ActivityEdgeRoute> route = sourceActivityEdgeRoute.stream().filter(entry ->
                            Objects.equals(entry.getLastNode(), node.getId())).collect(Collectors.toList());
                    if (it.getId().equals(instanceId)) {
                        // sourceEdge用来保存所有source可以访问到的边路径
                        sourceEdge.addAll(route.stream().map(ActivityEdgeRoute::getRoutes).collect(Collectors.toList()));
                    } else {
                        // 追加temp边
                        route.forEach(entry -> {
                            List<String> tempRoute = new ArrayList<>(entry.getRoutes());
                            tempRoute.add(it.getId());
                            MetaClassInstance tempEdge = internalUmlService.fetchInstance(it.getId(), projectId);
                            MetaClassInstance nextNode = internalUmlService.queryInstanceProperty(projectId, tempEdge, UMLDefinitionConstants.ActivityEdge_target);
                            if (Objects.nonNull(nextNode) && BooleanUtils.isTrue(isValidNode(projectId, sourceVisitedList, nextNode))) {
                                sourceActivityEdgeRoute.add(new ActivityEdgeRoute(tempRoute, nextNode.getId()));
                                sourceVisitList.add(nextNode);
                            }
                        });
                    }
                });
                sourceActivityEdgeRoute.removeIf(it -> it.getLastNode().equals(node.getId()));
                sourceVisitList.remove(node);
                // 该节点已访问过，下次不再访问
                sourceVisitedList.add(node.getId());
            }
        }
        return sourceEdge;
    }

    @NotNull
    private Boolean isValidNode(@NotNull String projectId, @NotNull List<String> visitedList, @NotNull MetaClassInstance node) {
        LogUtil.printSerializeOnlineLogs("projectId: {}, visitedList: {}, node: {}", projectId, visitedList, node);
        // 访问过的节点不再继续访问
        if (visitedList.contains(node.getId())) {
            return false;
        }
        // 非特殊节点不再访问
        return internalUmlService.checkInstanceType(projectId, node, UMLDefinitionConstants.ControlNode);
    }

    @NotNull
    public ModelResultVo updateItemFlow(UpdateItemFlowDTO updateItemFlowDto) {
        LogUtil.printSerializeOnlineLogs("updateItemFlowDto: ", updateItemFlowDto);
        final String projectId = updateItemFlowDto.getProjectId();
        final ModelResultVo modelResultVo = new ModelResultVo();

        MetaClassInstance instance = internalUmlService.fetchInstance(updateItemFlowDto.getItemFlow(), projectId);
        if (Objects.isNull(instance)) {
            return modelResultVo;
        }

        LocalTransaction transaction = transactionService.createTransaction(
                projectId, ModelActionName.UPDATE_PROPERTY);

        try {
            List<MetaClassInstance> itemFlowSetPropertiesResult = itemFlowSetProperties(updateItemFlowDto, instance, false);
            transactionService.commit(projectId);
            InstanceVoUtils.fillModelResultVo(modelResultVo, transaction);
            // 将添加的承载对象加入至modifyModel刷新画布
            if (StringUtils.isNotEmpty(updateItemFlowDto.getInstanceId())) {
                modelResultVo.getModifyModel().add(updateItemFlowDto.getInstanceId());
            }
            if (CollectionUtils.isNotEmpty(itemFlowSetPropertiesResult)) {
                modelResultVo.getModifyModel().addAll(itemFlowSetPropertiesResult.stream().map(BasicRElement::getId).collect(Collectors.toList()));
            }
        } catch (TransactionNotExistingException | LocalTransactionNotStartException e) {
            throw AbortExecutionException.build(ErrorCode.TRANSACTION_ERROR, e);
        } catch (Exception e) {
            transactionService.rollBack(projectId, transaction);
            throw AbortExecutionException.build(ErrorCode.PROPERTY_UPDATE_ERROR, e);
        }

        return modelResultVo;
    }

    @NotNull
    public List<String> queryItemFlowOfRelation(String projectId, String instanceId, String isAttributeField) {
        LogUtil.printOnlineLogs("projectId: {}, instanceId: {}, isAttributeField: {}", projectId, instanceId, isAttributeField);
        MetaClassInstance instance = internalUmlService.fetchInstance(instanceId, projectId);
        if (Objects.isNull(instance)) {
            return Collections.emptyList();
        }
        Set<String> givenTypes = internalUmlService.getGivenTypes(projectId, instance);
        if (!givenTypes.contains(UMLDefinitionConstants.Association) || !givenTypes.contains(UMLDefinitionConstants.Connector) ||
                !givenTypes.contains(UMLDefinitionConstants.ActivityEdge) || !givenTypes.contains(UMLDefinitionConstants.Message)) {
            return Collections.emptyList();
        }
        Map<String, List<MetaClassInstance>> informationFlowsMap = queryInformationFlows(projectId, instanceId);
        List<MetaClassInstance> informationFlows = informationFlowsMap.values().stream().flatMap(Collection::stream).collect(Collectors.toList());
        // 属性面板中过滤掉未实现的
        if (StringUtils.equals(isAttributeField, "true")) {
            List<ModelPropertyInfo> informationFlowModels = modelPropertyInfoService.createModelPropertyInfoList(projectId,
                    informationFlows,
                    Stream.of(UMLDefinitionConstants.InformationFlow_realizingConnector,
                            UMLDefinitionConstants.InformationFlow_realizingActivityEdge,
                            UMLDefinitionConstants.InformationFlow_realizingMessage,
                            UMLDefinitionConstants.InformationFlow_realization).collect(Collectors.toList()));
            informationFlows = informationFlowModels.stream().map(model -> {
                List<MetaClassInstance> realizingList;
                if (givenTypes.contains(UMLDefinitionConstants.Connector)) {
                    realizingList = model.queryListInstanceValue(UMLDefinitionConstants.InformationFlow_realizingConnector);
                } else if (givenTypes.contains(UMLDefinitionConstants.ActivityEdge)) {
                    realizingList = model.queryListInstanceValue(UMLDefinitionConstants.InformationFlow_realizingActivityEdge);
                } else if (givenTypes.contains(UMLDefinitionConstants.Message)) {
                    realizingList = model.queryListInstanceValue(UMLDefinitionConstants.InformationFlow_realizingMessage);
                } else {
                    realizingList = model.queryListInstanceValue(UMLDefinitionConstants.InformationFlow_realization);
                }

                if (realizingList.contains(instance)) {
                    return model.getInstance();
                }
                return null;
            }).filter(Objects::nonNull).collect(Collectors.toList());
        }

        return informationFlows.stream().map(BasicRElement::getId).collect(Collectors.toList());
    }

    @NotNull
    public ItemFlowVo queryItemFlowInfo(@NotNull String projectId, @NotNull String instanceId) {
        LogUtil.printOnlineLogs("queryItemFlowInfo -> projectId: {}, instanceId: {}", projectId, instanceId);
        MetaClassInstance instance = internalUmlService.fetchInstance(instanceId, projectId);
        if (Objects.isNull(instance)) {
            log.error("查询不到id为{}的模型", instanceId);
            throw AbortExecutionException.build(ErrorCode.MODEL_NO_EXIST);
        }

        ItemFlowVo itemFlowVo = new ItemFlowVo();

        ModelPropertyInfo itemFlowModel = modelPropertyInfoService.createSimpleModelPropertyInfo(projectId,
                instance,
                Stream.of(UMLDefinitionConstants.InformationFlow_informationSource,
                        UMLDefinitionConstants.InformationFlow_informationTarget,
                        UMLDefinitionConstants.InformationFlow_conveyed,
                        UMLDefinitionConstants.SysML_ItemFlow_itemProperty).collect(Collectors.toList()));

        List<MetaClassInstance> allInstances = Stream.of(
                itemFlowModel.queryListInstanceValue(UMLDefinitionConstants.InformationFlow_informationSource),
                itemFlowModel.queryListInstanceValue(UMLDefinitionConstants.InformationFlow_informationTarget),
                itemFlowModel.queryListInstanceValue(UMLDefinitionConstants.InformationFlow_conveyed),
                Collections.singletonList(itemFlowModel.queryInstanceValue(UMLDefinitionConstants.SysML_ItemFlow_itemProperty)))
                .flatMap(Collection::stream)
                .filter(Objects::nonNull).collect(Collectors.toList());

        QueryPropertyForm queryPropertyForm = internalUmlService.getQueryPropertyForm(allInstances, UMLDefinitionConstants.NamedElement_name);
        // 批量查询所有待查查询模型的name
        MofResultContainer instanceResult = internalUmlService.queryProperty(projectId, queryPropertyForm);
        // 批量查询所有模型的icon
        Map<String, String> iconMap = modelPropertyInfoService.queryIconBatch(projectId, new ArrayList<>(allInstances));

        List<MetaClassInstance> sourceList = itemFlowModel.queryListInstanceValue(UMLDefinitionConstants.InformationFlow_informationSource);
        itemFlowVo.setSource(fillItemFlowInfoByBatch(sourceList, instanceResult, iconMap).get(0));

        List<MetaClassInstance> targetList = itemFlowModel.queryListInstanceValue(UMLDefinitionConstants.InformationFlow_informationTarget);
        itemFlowVo.setTarget(fillItemFlowInfoByBatch(targetList, instanceResult, iconMap).get(0));

        List<MetaClassInstance> conveyeds = itemFlowModel.queryListInstanceValue(UMLDefinitionConstants.InformationFlow_conveyed);
        itemFlowVo.setConveyedItems(fillItemFlowInfoByBatch(conveyeds, instanceResult, iconMap));

        MetaClassInstance itemProperty = itemFlowModel.queryInstanceValue(UMLDefinitionConstants.SysML_ItemFlow_itemProperty);
        if (Objects.nonNull(itemProperty)) {
            itemFlowVo.setItemProperty(fillItemFlowInfoByBatch(Collections.singletonList(itemProperty), instanceResult, iconMap).get(0));
        }
        return itemFlowVo;
    }

    @NotNull
    private static List<SelectElementItem> fillItemFlowInfoByBatch(@NotNull List<MetaClassInstance> instances,
                                                                   @NotNull MofResultContainer mofResultContainer,
                                                                   @NotNull Map<String, String> iconMap) {
        LogUtil.printSerializeOnlineLogs("instances: {}, iconMap: {}", instances, iconMap);
        return instances.stream().map(instance -> {
            String id = instance.getId();
            SelectElementItem selectElementItem = new SelectElementItem();
            selectElementItem.setInstanceId(id);
            selectElementItem.setName(mofResultContainer.queryStringProperty(id, UMLDefinitionConstants.NamedElement_name));
            selectElementItem.setIcon(iconMap.get(instance.getId()));
            return selectElementItem;
        }).collect(Collectors.toList());
    }

    @NotNull
    private static Map<MetaClassInstance, SelectElementItem> fillItemFlowInfoByBatch(@NotNull List<MetaClassInstance> instances,
                                                                                     Map<String, ModelPropertyInfo> modelPropertyInfoMap,
                                                                                     Map<String, String> iconMap) {
        LogUtil.printSerializeOnlineLogs("instances: {}, iconMap: {}", instances, iconMap);
        return instances.stream().collect(Collectors.toMap(Function.identity(), value -> {
            String id = value.getId();
            SelectElementItem selectElementItem = new SelectElementItem();
            selectElementItem.setInstanceId(id);
            ModelPropertyInfo modelPropertyInfo = modelPropertyInfoMap.get(id);
            if (Objects.nonNull(modelPropertyInfo)) {
                selectElementItem.setName(modelPropertyInfo.queryStringValue(UMLDefinitionConstants.NamedElement_name));
            }
            selectElementItem.setIcon(iconMap.get(value.getId()));
            return selectElementItem;
        }, (k, v) -> k));
    }

    // 查询项流fromActivity和toActivity属性(传入项流id)
    @NotNull
    public ItemFlowFromToActivityVo queryItemFlowFromToActivity(String projectId, String sourceId, String targetId) {
        LogUtil.printOnlineLogs("projectId: {}, sourceId: {}, targetId: {}", projectId, sourceId, targetId);
        Map<String, MetaClassInstance> instanceMap = internalUmlService.fetchInstances(
                Stream.of(sourceId, targetId).collect(Collectors.toList()), projectId);
        MetaClassInstance source = instanceMap.get(sourceId);
        MetaClassInstance target = instanceMap.get(targetId);

        QueryPropertyForm queryPropertyForm = internalUmlService.getQueryPropertyForm(
                new ArrayList<>(instanceMap.values()),
                UMLDefinitionConstants.NamedElement_allocatedFrom);
        MofResultContainer mofResultContainer = internalUmlService.queryProperty(projectId, queryPropertyForm);

        List<MetaClassInstance> fromActivityList = mofResultContainer.queryListInstanceProperty(
                source.getId(), UMLDefinitionConstants.NamedElement_allocatedFrom);
        List<MetaClassInstance> toActivityList = mofResultContainer.queryListInstanceProperty(
                target.getId(), UMLDefinitionConstants.NamedElement_allocatedFrom);

        List<MetaClassInstance> activityList = Stream.concat(fromActivityList.stream(), toActivityList.stream())
                .collect(Collectors.toList());
        QueryPropertyForm queryActivityForm = internalUmlService.getQueryPropertyForm(activityList, UMLDefinitionConstants.NamedElement_name);
        MofResultContainer activityResult = internalUmlService.queryProperty(projectId, queryActivityForm);
        Map<String, String> iconMap = modelPropertyInfoService.queryIconBatch(projectId, activityList);

        ItemFlowFromToActivityVo itemFlowFromToActivityVo = new ItemFlowFromToActivityVo();
        itemFlowFromToActivityVo.setFromActivity(fillItemFlowInfoByBatch(fromActivityList, activityResult, iconMap));
        itemFlowFromToActivityVo.setToActivity(fillItemFlowInfoByBatch(toActivityList, activityResult, iconMap));
        return itemFlowFromToActivityVo;
    }

    @NotNull
    public Boolean validActivityEdgeCanCarryItemFlow(String projectId, String instanceId) {
        LogUtil.printOnlineLogs("validActivityEdgeCanCarryItemFlow -> projectId: {}, instanceId: {}", projectId, instanceId);
        MetaClassInstance instance = internalUmlService.fetchInstance(instanceId, projectId);
        if (Objects.isNull(instance)) {
            log.error("查询边不存在");
            throw AbortExecutionException.build(ErrorCode.MODEL_NO_EXIST);
        }
        ItemFlowEndListVo itemFlowEndListVo = internalItemFlowService.queryOnTheActivityEdge(projectId, instance);
        return CollectionUtils.isNotEmpty(itemFlowEndListVo.getSource()) && CollectionUtils.isNotEmpty(itemFlowEndListVo.getTarget());
    }

    @NotNull
    public Boolean validExistsItemFlowManager(String projectId, String instanceId) {
        LogUtil.printOnlineLogs("validExistsItemFlowManager -> projectId: {}, instanceId: {}", projectId, instanceId);
        Map<String, List<MetaClassInstance>> informationFlowMap = queryInformationFlows(projectId, instanceId);
        List<MetaClassInstance> informationFlowList = new ArrayList<>();
        if (MapUtils.isNotEmpty(informationFlowMap)) {
            informationFlowList.addAll(informationFlowMap.get(CURRENT));
            informationFlowList.addAll(informationFlowMap.get(GENERAL));
            informationFlowList.addAll(informationFlowMap.get(AGGREGATION));
        }
        informationFlowList = informationFlowList.stream().distinct().collect(Collectors.toList());
        return CollectionUtils.isNotEmpty(informationFlowList);
    }

    /**
     * 查询项流
     *
     * @param projectId
     * @param instanceId
     * @return java.util.Map<java.lang.String, java.util.List < com.huawang.model.instances.MetaClassInstance>>
     * @author baibf
     * @date 2023/08/17 18:40
     */
    @NotNull
    private Map<String, List<MetaClassInstance>> queryInformationFlows(String projectId, String instanceId) {
        LogUtil.printOnlineLogs("queryInformationFlows -> projectId: {}, instanceId: {}", projectId, instanceId);
        Map<String, List<MetaClassInstance>> informationFlowMap = new HashMap<>();
        MetaClassInstance instance = internalUmlService.fetchExistInstance(instanceId, projectId);
        // 从承载模型获取项流的两端
        ItemFlowEndListVo itemFlowEndListVo = internalItemFlowService.queryItemFlowEnds(projectId, instanceId);

        List<String> sourceIds = itemFlowEndListVo.getSource();
        List<String> targetIds = itemFlowEndListVo.getTarget();

        // 新增规则:项流管理器中需要查询出符合(部件属性->部件属性)、(部件属性类型->部件属性类型)的所有项流
        // 新增(部件属性->部件属性)项流
        if (internalUmlService.checkInstanceType(projectId, instance, UMLDefinitionConstants.Connector)) {
            List<String> fromActivityIds = itemFlowEndListVo.getUnAllocatedSource();
            List<String> toActivityIds = itemFlowEndListVo.getUnAllocatedTarget();
            if (CollectionUtils.isNotEmpty(fromActivityIds)) {
                sourceIds.addAll(fromActivityIds);
            }
            if (CollectionUtils.isNotEmpty(toActivityIds)) {
                targetIds.addAll(toActivityIds);
            }
        }

        if (CollectionUtils.isEmpty(sourceIds) || CollectionUtils.isEmpty(targetIds)) {
            return informationFlowMap;
        }

        Map<String, MetaClassInstance> instanceMap = internalUmlService.fetchInstances(
                Stream.concat(sourceIds.stream(), targetIds.stream()).collect(Collectors.toList()), projectId);
        List<MetaClassInstance> sourceList = sourceIds.stream().map(instanceMap::get).collect(Collectors.toList());
        List<MetaClassInstance> targetList = targetIds.stream().map(instanceMap::get).collect(Collectors.toList());
        // 查询当前项流
        List<MetaClassInstance> currentItemFlow = getCurrentItemFlow(projectId, instance, sourceList, targetList);
        informationFlowMap.put(CURRENT, currentItemFlow);
        // 查询继承链存在的项流
        List<MetaClassInstance> generalItemFlow = getGeneralItemFlow(projectId, instance, sourceList, targetList);
        generalItemFlow.removeAll(currentItemFlow);
        informationFlowMap.put(GENERAL, generalItemFlow);
        // 查询聚合链间存在的项流
        List<MetaClassInstance> aggregationItemFlow = getAggregationItemFlow(projectId, instance, sourceList, targetList);
        aggregationItemFlow.removeAll(currentItemFlow);
        informationFlowMap.put(AGGREGATION, aggregationItemFlow);
        return informationFlowMap;
    }

    /**
     * description:查询source-> target间存在的项流
     */
    @NotNull
    private List<MetaClassInstance> getCurrentItemFlow(@NotNull String projectId,
                                                       @NotNull MetaClassInstance instance,
                                                       @NotNull List<MetaClassInstance> sourceList,
                                                       @NotNull List<MetaClassInstance> targetList) {
        LogUtil.printSerializeOnlineLogs("getCurrentItemFlow -> projectId: {}, instance: {}, sourceList: {}, targetList: {}",
                projectId, instance, sourceList, targetList);
        QueryPropertyForm queryPropertyForm = internalUmlService.getQueryPropertyForm(
                Stream.concat(sourceList.stream(), targetList.stream()).collect(Collectors.toList()),
                Stream.of(UMLDefinitionConstants.A_informationSource_informationFlow_informationFlow,
                        UMLDefinitionConstants.A_informationTarget_informationFlow_informationFlow).collect(Collectors.toList()));
        MofResultContainer itemFlowEndResult = internalUmlService.queryProperty(projectId, queryPropertyForm);

        List<MetaClassInstance> sourceInformationFlowList = sourceList.stream().flatMap(source ->
                itemFlowEndResult.queryListInstanceProperty(
                        source.getId(), UMLDefinitionConstants.A_informationSource_informationFlow_informationFlow).stream())
                .collect(Collectors.toList());
        List<MetaClassInstance> targetInformationFlowList = targetList.stream().flatMap(target ->
                itemFlowEndResult.queryListInstanceProperty(
                        target.getId(), UMLDefinitionConstants.A_informationTarget_informationFlow_informationFlow).stream())
                .collect(Collectors.toList());
        // 当前source和target的项流
        List<MetaClassInstance> informationFlowList = sourceInformationFlowList.stream().filter(targetInformationFlowList::contains).collect(Collectors.toList());
        // 连接器需要考虑双向项流的问题
        if (internalUmlService.checkInstanceType(projectId, instance, UMLDefinitionConstants.Connector)) {
            List<MetaClassInstance> reverseSourceInformationFlowList = sourceList.stream().flatMap(source ->
                    itemFlowEndResult.queryListInstanceProperty(
                            source.getId(), UMLDefinitionConstants.A_informationTarget_informationFlow_informationFlow).stream())
                    .collect(Collectors.toList());
            List<MetaClassInstance> reverseTargetInformationFlowList = targetList.stream().flatMap(target ->
                    itemFlowEndResult.queryListInstanceProperty(
                            target.getId(), UMLDefinitionConstants.A_informationSource_informationFlow_informationFlow).stream())
                    .collect(Collectors.toList());
            informationFlowList.addAll(reverseSourceInformationFlowList.stream().filter(reverseTargetInformationFlowList::contains).collect(Collectors.toList()));
        }
        return informationFlowList.stream().distinct().collect(Collectors.toList());
    }

    /**
     * description:查询source-> target泛化链间存在的项流
     */
    @NotNull
    private List<MetaClassInstance> getGeneralItemFlow(@NotNull String projectId,
                                                       @NotNull MetaClassInstance instance,
                                                       @NotNull List<MetaClassInstance> sourceList,
                                                       @NotNull List<MetaClassInstance> targetList) {
        LogUtil.printSerializeOnlineLogs("getGeneralItemFlow -> projectId: {}, instance: {}, sourceList: {}, targetList: {}",
                projectId, instance, sourceList, targetList);
        // 泛化链在内存中，等mof提供批量的接口
        List<MetaClassInstance> sourceGenerals = sourceList.stream().flatMap(source ->
                internalUmlService.findGeneralsCascade(projectId, source.getId(), true).stream())
                .collect(Collectors.toList());
        List<MetaClassInstance> targetGenerals = targetList.stream().flatMap(target ->
                internalUmlService.findGeneralsCascade(projectId, target.getId(), true).stream())
                .collect(Collectors.toList());

        QueryPropertyForm generalForm = internalUmlService.getQueryPropertyForm(
                Stream.concat(sourceGenerals.stream(), targetGenerals.stream()).collect(Collectors.toList()),
                Stream.of(UMLDefinitionConstants.A_informationSource_informationFlow_informationFlow,
                        UMLDefinitionConstants.A_informationTarget_informationFlow_informationFlow).collect(Collectors.toList()));
        MofResultContainer generalResult = internalUmlService.queryProperty(projectId, generalForm);

        List<MetaClassInstance> sourceGeneralInformationList = sourceGenerals.stream().flatMap(sourceGeneral ->
                generalResult.queryListInstanceProperty(sourceGeneral.getId(),
                        UMLDefinitionConstants.A_informationSource_informationFlow_informationFlow).stream()).collect(Collectors.toList());
        List<MetaClassInstance> targetGeneralInformationList = targetGenerals.stream().flatMap(targetGeneral ->
                generalResult.queryListInstanceProperty(targetGeneral.getId(),
                        UMLDefinitionConstants.A_informationTarget_informationFlow_informationFlow).stream()).collect(Collectors.toList());
        // 继承的项流
        List<MetaClassInstance> generalInformationList = sourceGeneralInformationList.stream().filter(targetGeneralInformationList::contains).collect(Collectors.toList());
        if (internalUmlService.checkInstanceType(projectId, instance, UMLDefinitionConstants.Connector)) {
            List<MetaClassInstance> reverseSourceGeneralInformationList = sourceGenerals.stream().flatMap(sourceGeneral ->
                    generalResult.queryListInstanceProperty(sourceGeneral.getId(),
                            UMLDefinitionConstants.A_informationTarget_informationFlow_informationFlow).stream()).collect(Collectors.toList());
            List<MetaClassInstance> reverseTargetGeneralInformationList = targetGenerals.stream().flatMap(targetGeneral ->
                    generalResult.queryListInstanceProperty(targetGeneral.getId(),
                            UMLDefinitionConstants.A_informationSource_informationFlow_informationFlow).stream()).collect(Collectors.toList());
            generalInformationList.addAll(reverseSourceGeneralInformationList.stream().filter(reverseTargetGeneralInformationList::contains).collect(Collectors.toList()));
        }
        return generalInformationList.stream().distinct().collect(Collectors.toList());
    }

    /**
     * description:查询source-> target聚合链间存在的项流
     */
    @NotNull
    private List<MetaClassInstance> getAggregationItemFlow(@NotNull String projectId,
                                                           @NotNull MetaClassInstance instance,
                                                           @NotNull List<MetaClassInstance> sourceList,
                                                           @NotNull List<MetaClassInstance> targetList) {
        LogUtil.printSerializeOnlineLogs("getAggregationItemFlow -> projectId: {}, instance: {}, sourceList: {}, targetList: {}",
                projectId, instance, sourceList, targetList);
        final Map<String, Set<MetaClassInstance>> sourceAggregationMap = new HashMap<>();
        internalUmlService.findAggregationReverseCascades(projectId, new ArrayList<>(sourceList), new HashSet<>(), sourceAggregationMap);
        final Map<String, Set<MetaClassInstance>> targetAggregationMap = new HashMap<>();
        internalUmlService.findAggregationReverseCascades(projectId, new ArrayList<>(targetList), new HashSet<>(), targetAggregationMap);
        List<MetaClassInstance> sourceAggregationList = sourceAggregationMap.values().stream()
                .flatMap(Collection::stream).collect(Collectors.toList());
        List<MetaClassInstance> targetAggregationList = targetAggregationMap.values().stream()
                .flatMap(Collection::stream).collect(Collectors.toList());
        // findAggregationElement当前边的source和target
        sourceAggregationList.addAll(sourceList);
        targetAggregationList.addAll(targetList);

        QueryPropertyForm aggregationForm = internalUmlService.getQueryPropertyForm(
                Stream.concat(sourceAggregationList.stream(), targetAggregationList.stream()).collect(Collectors.toList()),
                Stream.of(UMLDefinitionConstants.A_informationSource_informationFlow_informationFlow,
                        UMLDefinitionConstants.A_informationTarget_informationFlow_informationFlow).collect(Collectors.toList()));
        MofResultContainer aggregationResult = internalUmlService.queryProperty(projectId, aggregationForm);

        List<MetaClassInstance> sourceAggregationInformationList = sourceAggregationList.stream().flatMap(sourceAggregation ->
                aggregationResult.queryListInstanceProperty(sourceAggregation.getId(),
                        UMLDefinitionConstants.A_informationSource_informationFlow_informationFlow).stream()).collect(Collectors.toList());
        List<MetaClassInstance> targetAggregationInformationList = targetAggregationList.stream().flatMap(targetAggregation ->
                aggregationResult.queryListInstanceProperty(targetAggregation.getId(),
                        UMLDefinitionConstants.A_informationTarget_informationFlow_informationFlow).stream()).collect(Collectors.toList());
        sourceAggregationInformationList = sourceAggregationInformationList.stream().distinct().collect(Collectors.toList());
        targetAggregationInformationList = targetAggregationInformationList.stream().distinct().collect(Collectors.toList());
        // 聚合的项流
        List<MetaClassInstance> aggregationInformationList = sourceAggregationInformationList.stream().filter(targetAggregationInformationList::contains).collect(Collectors.toList());
        if (internalUmlService.checkInstanceType(projectId, instance, UMLDefinitionConstants.Connector)) {
            List<MetaClassInstance> reverseSourceAggregationInformationList = sourceAggregationList.stream().flatMap(sourceAggregation ->
                    aggregationResult.queryListInstanceProperty(sourceAggregation.getId(),
                            UMLDefinitionConstants.A_informationTarget_informationFlow_informationFlow).stream()).collect(Collectors.toList());
            List<MetaClassInstance> reverseTargetAggregationInformationList = targetAggregationList.stream().flatMap(targetAggregation ->
                    aggregationResult.queryListInstanceProperty(targetAggregation.getId(),
                            UMLDefinitionConstants.A_informationSource_informationFlow_informationFlow).stream()).collect(Collectors.toList());
            aggregationInformationList.addAll(reverseSourceAggregationInformationList.stream().filter(reverseTargetAggregationInformationList::contains).collect(Collectors.toList()));
        }
        return aggregationInformationList.stream().distinct().collect(Collectors.toList());
    }

    @NotNull
    public List<ItemFlowManagerInfoVo> queryItemFlowManagerInfo(String projectId, String instanceId) {
        LogUtil.printOnlineLogs("queryItemFlowManagerInfo -> projectId: {}, instanceId: {}", projectId, instanceId);
        final MetaClassInstance instance = internalUmlService.fetchInstance(instanceId, projectId);
        Set<String> instanceGivenTypes = internalUmlService.getGivenTypes(projectId, instance);

        if (instanceGivenTypes.contains(UMLDefinitionConstants.Connector)
                || instanceGivenTypes.contains(UMLDefinitionConstants.ActivityEdge)
                || instanceGivenTypes.contains(UMLDefinitionConstants.Message)
                || instanceGivenTypes.contains(UMLDefinitionConstants.Association)) {

            Map<String, List<MetaClassInstance>> informationFlowMap = queryInformationFlows(projectId, instanceId);
            if (MapUtils.isEmpty(informationFlowMap)) {
                return Collections.emptyList();
            }
            // 当前source和target的项流
            List<MetaClassInstance> informationFlowList = informationFlowMap.get(CURRENT);
            // 继承的项流
            List<MetaClassInstance> generalInformationList = informationFlowMap.get(GENERAL);
            // 聚合的项流
            List<MetaClassInstance> aggregationInformationList = informationFlowMap.get(AGGREGATION);
            // 当前项流信息
            List<ItemFlowManagerInfoVo> itemFlowManagerInfoVos = queryAllItemFlowInfo(projectId, informationFlowList,
                    instance, instanceGivenTypes);
            // 继承的项流信息
            List<ItemFlowManagerInfoVo> generalItemFlowManagerInfoVos = queryAllItemFlowInfo(projectId,
                    generalInformationList, instance, instanceGivenTypes);
            generalItemFlowManagerInfoVos.forEach(generalItemFlowManagerInfoVo -> generalItemFlowManagerInfoVo.setInherited(true));
            itemFlowManagerInfoVos.addAll(generalItemFlowManagerInfoVos);
            // 聚合的项流信息
            List<ItemFlowManagerInfoVo> aggregationItemFlowManagerInfoVos = queryAllItemFlowInfo(projectId,
                    aggregationInformationList, instance, instanceGivenTypes);
            aggregationItemFlowManagerInfoVos.forEach(aggregationItemFlowManagerInfoVo -> aggregationItemFlowManagerInfoVo.setAggregated(true));
            itemFlowManagerInfoVos.addAll(aggregationItemFlowManagerInfoVos);

            return itemFlowManagerInfoVos;
        }

        return Collections.emptyList();
    }

    @NotNull
    private List<ItemFlowManagerInfoVo> queryAllItemFlowInfo(String projectId,
                                                             List<MetaClassInstance> informationFlows,
                                                             MetaClassInstance instance,
                                                             Set<String> givenTypes) {
        LogUtil.printSerializeOnlineLogs("projectId: {}, informationFlows: {}, instance: {}, givenTypes: {}",
                projectId, informationFlows, instance, givenTypes);
        List<ModelPropertyInfo> informationFlowModels = modelPropertyInfoService.createModelPropertyInfoList(projectId,
                informationFlows,
                Stream.of(UMLDefinitionConstants.InformationFlow_conveyed,
                        UMLDefinitionConstants.SysML_ItemFlow_itemProperty,
                        UMLDefinitionConstants.InformationFlow_informationSource,
                        UMLDefinitionConstants.InformationFlow_informationTarget,
                        UMLDefinitionConstants.SysML_ItemFlow_fromActivity,
                        UMLDefinitionConstants.SysML_ItemFlow_toActivity,
                        UMLDefinitionConstants.InformationFlow_realizingConnector,
                        UMLDefinitionConstants.InformationFlow_realizingActivityEdge,
                        UMLDefinitionConstants.InformationFlow_realizingMessage,
                        UMLDefinitionConstants.InformationFlow_realization).collect(Collectors.toList()));

        List<MetaClassInstance> allInstances = informationFlowModels.stream().flatMap(it -> Stream.of(
                it.queryListInstanceValue(UMLDefinitionConstants.InformationFlow_conveyed),
                Collections.singletonList(it.queryInstanceValue(UMLDefinitionConstants.SysML_ItemFlow_itemProperty)),
                it.queryListInstanceValue(UMLDefinitionConstants.InformationFlow_informationSource),
                it.queryListInstanceValue(UMLDefinitionConstants.InformationFlow_informationTarget),
                it.queryListInstanceValue(UMLDefinitionConstants.SysML_ItemFlow_fromActivity),
                it.queryListInstanceValue(UMLDefinitionConstants.SysML_ItemFlow_toActivity))
                .flatMap(Collection::stream))
                .filter(Objects::nonNull).collect(Collectors.toList());

        QueryPropertyForm queryPropertyForm = internalUmlService.getQueryPropertyForm(allInstances, UMLDefinitionConstants.NamedElement_name);
        // 批量查询所有待查查询模型的name
        MofResultContainer instancePropertyContainer = internalUmlService.queryProperty(projectId, queryPropertyForm);
        // 批量查询所有模型的icon
        Map<String, String> iconMap = modelPropertyInfoService.queryIconBatch(projectId, new ArrayList<>(allInstances));

        return informationFlowModels.stream().map(informationFlowModel -> {
            ItemFlowManagerInfoVo itemFlowManagerInfoVo = new ItemFlowManagerInfoVo();
            itemFlowManagerInfoVo.setItemFlowId(informationFlowModel.getInstanceId());

            if (givenTypes.contains(UMLDefinitionConstants.Connector)) {
                List<MetaClassInstance> realizingConnectorList = informationFlowModel.queryListInstanceValue(
                        UMLDefinitionConstants.InformationFlow_realizingConnector);
                itemFlowManagerInfoVo.setRealized(realizingConnectorList.contains(instance));
            } else if (givenTypes.contains(UMLDefinitionConstants.ActivityEdge)) {
                List<MetaClassInstance> realizingActivityEdgeList = informationFlowModel.queryListInstanceValue(
                        UMLDefinitionConstants.InformationFlow_realizingActivityEdge);
                itemFlowManagerInfoVo.setRealized(realizingActivityEdgeList.contains(instance));
            } else if (givenTypes.contains(UMLDefinitionConstants.Message)) {
                List<MetaClassInstance> realizingMessageList = informationFlowModel.queryListInstanceValue(
                        UMLDefinitionConstants.InformationFlow_realizingMessage);
                itemFlowManagerInfoVo.setRealized(realizingMessageList.contains(instance));
            } else {
                List<MetaClassInstance> realizationList = informationFlowModel.queryListInstanceValue(
                        UMLDefinitionConstants.InformationFlow_realization);
                itemFlowManagerInfoVo.setRealized(realizationList.contains(instance));
            }
            List<MetaClassInstance> conveyedList = informationFlowModel.queryListInstanceValue(UMLDefinitionConstants.InformationFlow_conveyed);
            MetaClassInstance itemProperty = informationFlowModel.queryInstanceValue(UMLDefinitionConstants.SysML_ItemFlow_itemProperty);
            List<MetaClassInstance> sourceList = informationFlowModel.queryListInstanceValue(UMLDefinitionConstants.InformationFlow_informationSource);
            List<MetaClassInstance> targetList = informationFlowModel.queryListInstanceValue(UMLDefinitionConstants.InformationFlow_informationTarget);
            List<MetaClassInstance> fromActivityList = informationFlowModel.queryListInstanceValue(UMLDefinitionConstants.SysML_ItemFlow_fromActivity);
            List<MetaClassInstance> toActivityList = informationFlowModel.queryListInstanceValue(UMLDefinitionConstants.SysML_ItemFlow_toActivity);

            itemFlowManagerInfoVo.setConveyed(fillItemFlowInfoByBatch(conveyedList, instancePropertyContainer, iconMap));
            if (CollectionUtils.isNotEmpty(sourceList)) {
                itemFlowManagerInfoVo.setSource(fillItemFlowInfoByBatch(sourceList, instancePropertyContainer, iconMap).get(0));
            }
            if (CollectionUtils.isNotEmpty(targetList)) {
                itemFlowManagerInfoVo.setTarget(fillItemFlowInfoByBatch(targetList, instancePropertyContainer, iconMap).get(0));
            }
            itemFlowManagerInfoVo.setFromActivity(fillItemFlowInfoByBatch(fromActivityList, instancePropertyContainer, iconMap));
            itemFlowManagerInfoVo.setToActivity(fillItemFlowInfoByBatch(toActivityList, instancePropertyContainer, iconMap));
            if (Objects.nonNull(itemProperty)) {
                SelectElementItem selectElementItem = fillItemFlowInfoByBatch(Collections.singletonList(itemProperty), instancePropertyContainer, iconMap).get(0);
                MetaClassInstance itemPropertyType = internalUmlService.queryInstanceProperty(projectId, itemProperty, UMLDefinitionConstants.TypedElement_type);
                String itemPropertyTypeName = internalUmlService.queryStringProperty(projectId, itemPropertyType,
                        UMLDefinitionConstants.NamedElement_name);
                if (Objects.nonNull(itemPropertyTypeName)) {
                    selectElementItem.setName(selectElementItem.getName().concat(":").concat(itemPropertyTypeName));
                }
                itemFlowManagerInfoVo.setItemProperty(selectElementItem);
            }

            return itemFlowManagerInfoVo;
        }).collect(Collectors.toList());
    }

    @NotNull
    public List<String> queryUnrealizedItemFlow(String projectId, String instanceId) {
        LogUtil.printOnlineLogs("queryUnrealizedItemFlow -> projectId: {}, instanceId: {}", projectId, instanceId);
        final MetaClassInstance instance = internalUmlService.fetchInstance(instanceId, projectId);
        Set<String> instanceGivenTypes = internalUmlService.getGivenTypes(projectId, instance);
        // 查询项流
        Map<String, List<MetaClassInstance>> informationFlowMap = queryInformationFlows(projectId, instanceId);
        List<MetaClassInstance> informationFlowList = new ArrayList<>();
        if (MapUtils.isNotEmpty(informationFlowMap)) {
            informationFlowList.addAll(informationFlowMap.get(CURRENT));
            informationFlowList.addAll(informationFlowMap.get(GENERAL));
            informationFlowList.addAll(informationFlowMap.get(AGGREGATION));
        }
        informationFlowList = informationFlowList.stream().distinct().collect(Collectors.toList());

        List<ModelPropertyInfo> informationFlowModels = modelPropertyInfoService.createModelPropertyInfoList(projectId,
                informationFlowList,
                Stream.of(UMLDefinitionConstants.InformationFlow_realizingConnector,
                        UMLDefinitionConstants.InformationFlow_realizingActivityEdge,
                        UMLDefinitionConstants.InformationFlow_realizingMessage,
                        UMLDefinitionConstants.InformationFlow_realization).collect(Collectors.toList()));

        if (instanceGivenTypes.contains(UMLDefinitionConstants.Connector)) {
            return informationFlowModels.stream()
                    .filter(it -> !it.queryListInstanceValue(UMLDefinitionConstants.InformationFlow_realizingConnector).contains(instance))
                    .map(ModelPropertyInfo::getInstanceId)
                    .collect(Collectors.toList());
        } else if (instanceGivenTypes.contains(UMLDefinitionConstants.ActivityEdge)) {
            return informationFlowModels.stream()
                    .filter(it -> !it.queryListInstanceValue(UMLDefinitionConstants.InformationFlow_realizingActivityEdge).contains(instance))
                    .map(ModelPropertyInfo::getInstanceId)
                    .collect(Collectors.toList());
        } else if (instanceGivenTypes.contains(UMLDefinitionConstants.Message)) {
            return informationFlowModels.stream()
                    .filter(it -> !it.queryListInstanceValue(UMLDefinitionConstants.InformationFlow_realizingMessage).contains(instance))
                    .map(ModelPropertyInfo::getInstanceId)
                    .collect(Collectors.toList());
        } else {
            return informationFlowModels.stream()
                    .filter(it -> !it.queryListInstanceValue(UMLDefinitionConstants.InformationFlow_realization).contains(instance))
                    .map(ModelPropertyInfo::getInstanceId)
                    .collect(Collectors.toList());
        }
    }

    @NotNull
    public ModelResultVo removeConveyed(@RequestBody ConveyedRemoveDTO conveyedRemoveDTO) {
        LogUtil.printSerializeOnlineLogs("conveyedRemoveDTO: ", conveyedRemoveDTO);
        final String projectId = conveyedRemoveDTO.getProjectId();
        final String instanceId = conveyedRemoveDTO.getInstanceId();
        final String relationId = conveyedRemoveDTO.getRelationId();
        Map<String, MetaClassInstance> instanceMap = internalUmlService.fetchInstances(
                Stream.of(instanceId, relationId).collect(Collectors.toList()), projectId);

        MetaClassInstance instance = instanceMap.get(instanceId);
        if (Objects.isNull(instance)) {
            log.error("项流{}不存在", conveyedRemoveDTO.getInstanceId());
            throw AbortExecutionException.build(ErrorCode.MODEL_NO_EXIST);
        }
        ModelResultVo modelResultVo = new ModelResultVo();
        LocalTransaction transaction = transactionService.createTransaction(projectId, DELETE_MODEL);
        try {
            MetaClassInstance removeInstance = internalUmlService.fetchInstance(conveyedRemoveDTO.getRemoveInstanceId(), projectId);
            if (Objects.nonNull(removeInstance)) {
                umlService.removeModel(projectId, instance.getId(), UMLDefinitionConstants.InformationFlow_conveyed, removeInstance);
            }
            List<MetaClassInstance> conveyedList = internalUmlService.queryListInstanceProperty(projectId, instance,
                    UMLDefinitionConstants.InformationFlow_conveyed);
            if (CollectionUtils.isEmpty(conveyedList)) {
                MetaClassInstance relation = instanceMap.get(relationId);
                if (Objects.nonNull(relation)) {
                    Set<String> givenTypes = internalUmlService.getGivenTypes(projectId, relation);
                    if (givenTypes.contains(UMLDefinitionConstants.Connector)) {
                        umlService.removeModel(projectId, instance.getId(),
                                UMLDefinitionConstants.InformationFlow_realizingConnector, relation);
                    } else if (givenTypes.contains(UMLDefinitionConstants.ActivityEdge)) {
                        umlService.removeModel(projectId, instance.getId(),
                                UMLDefinitionConstants.InformationFlow_realizingActivityEdge, relation);
                    } else if (givenTypes.contains(UMLDefinitionConstants.Message)) {
                        umlService.removeModel(projectId, instance.getId(),
                                UMLDefinitionConstants.InformationFlow_realizingMessage, relation);
                    } else {
                        umlService.removeModel(projectId, instance.getId(),
                                UMLDefinitionConstants.InformationFlow_realization, relation);
                    }
                }
            }

            transactionService.commit(projectId);
            modelResultVo.setInstanceId(conveyedRemoveDTO.getInstanceId());
            InstanceVoUtils.fillModelResultVo(modelResultVo, transaction);
            modelResultVo.getModifyModel().add(conveyedRemoveDTO.getRelationId());
        } catch (TransactionNotExistingException | LocalTransactionNotStartException e) {
            throw AbortExecutionException.build(ErrorCode.TRANSACTION_ERROR);
        } catch (Exception e) {
            transactionService.rollBack(projectId, transaction);
            throw AbortExecutionException.build(ErrorCode.SERVICE_ERROR, e);
        }
        return modelResultVo;
    }

    @NotNull
    public List<ItemFlowRouteVo> queryActivityEdgeItemFlowAllRoute(@NotNull String projectId, @NotNull String instanceId) {
        LogUtil.printOnlineLogs("queryActivityEdgeItemFlowAllRoute -> projectId: {}, instanceId: {}", projectId, instanceId);
        Map<String, List<MetaClassInstance>> informationFlowMap = queryInformationFlows(projectId, instanceId);
        if (informationFlowMap.isEmpty()) {
            return Collections.emptyList();
        }
        final MetaClassInstance instance = internalUmlService.fetchInstance(instanceId, projectId);
        Set<String> instanceGivenTypes = internalUmlService.getGivenTypes(projectId, instance);
        List<ItemFlowRouteVo> itemFlowRouteVoList = new ArrayList<>();
        // current、泛化、聚合Map获取models
        for (Map.Entry<String, List<MetaClassInstance>> entry : informationFlowMap.entrySet()) {
            String key = entry.getKey();
            List<MetaClassInstance> value = entry.getValue();
            List<ModelPropertyInfo> informationFlowModels = modelPropertyInfoService.createModelPropertyInfoList(projectId,
                    value,
                    Stream.of(UMLDefinitionConstants.InformationFlow_realizingConnector,
                            UMLDefinitionConstants.InformationFlow_realizingActivityEdge,
                            UMLDefinitionConstants.InformationFlow_realizingMessage,
                            UMLDefinitionConstants.InformationFlow_realization,
                            UMLDefinitionConstants.InformationFlow_informationSource,
                            UMLDefinitionConstants.InformationFlow_informationTarget).collect(Collectors.toList()));
            // 过滤已被实现的项流
            List<ModelPropertyInfo> unRealizingInformationFlow;
            if (instanceGivenTypes.contains(UMLDefinitionConstants.Connector)) {
                unRealizingInformationFlow = informationFlowModels.stream()
                        .filter(it -> !it.queryListInstanceValue(UMLDefinitionConstants.InformationFlow_realizingConnector).contains(instance))
                        .collect(Collectors.toList());
            } else if (instanceGivenTypes.contains(UMLDefinitionConstants.ActivityEdge)) {
                unRealizingInformationFlow = informationFlowModels.stream()
                        .filter(it -> !it.queryListInstanceValue(UMLDefinitionConstants.InformationFlow_realizingActivityEdge).contains(instance))
                        .collect(Collectors.toList());
            } else if (instanceGivenTypes.contains(UMLDefinitionConstants.Message)) {
                unRealizingInformationFlow = informationFlowModels.stream()
                        .filter(it -> !it.queryListInstanceValue(UMLDefinitionConstants.InformationFlow_realizingMessage).contains(instance))
                        .collect(Collectors.toList());
            } else {
                unRealizingInformationFlow = informationFlowModels.stream()
                        .filter(it -> !it.queryListInstanceValue(UMLDefinitionConstants.InformationFlow_realization).contains(instance))
                        .collect(Collectors.toList());
            }

            if (CollectionUtils.isEmpty(unRealizingInformationFlow)) {
                log.info("{}组项流不存在未实现的项流", key);
                continue;
            }
            unRealizingInformationFlow.forEach(it -> {
                List<MetaClassInstance> informationSource = it.queryListInstanceValue(UMLDefinitionConstants.InformationFlow_informationSource);
                List<MetaClassInstance> informationTarget = it.queryListInstanceValue(UMLDefinitionConstants.InformationFlow_informationTarget);
                ItemFlowRouteVo itemFlowRouteVo = new ItemFlowRouteVo();
                List<String> allRealizingRoute = new ArrayList<>();
                // current且为活动边 需要添加除当前边外的所有实现路径
                if (key.equals(CURRENT) && instanceGivenTypes.contains(UMLDefinitionConstants.ActivityEdge)) {
                    allRealizingRoute.addAll(findAllRealizing(projectId, instanceId, informationSource.get(0).getId(), informationTarget.get(0).getId()));
                }
                // 增加当前边
                allRealizingRoute.add(instanceId);
                itemFlowRouteVo.setItemFlowRoute(allRealizingRoute);
                itemFlowRouteVo.setItemFlowId(it.getInstanceId());
                itemFlowRouteVoList.add(itemFlowRouteVo);
            });
        }
        return itemFlowRouteVoList;
    }

    @NotNull
    public List<ItemFlowRouteVo> queryCancelItemFlowAllRoute(CancelItemFlowAllRouteDTO cancelItemFlowAllRouteDto) {
        LogUtil.printSerializeOnlineLogs("cancelItemFlowAllRouteDto: ", cancelItemFlowAllRouteDto);
        final String projectId = cancelItemFlowAllRouteDto.getProjectId();
        final List<String> informationFlowIdList = cancelItemFlowAllRouteDto.getInformationFlowIdList();
        final String instanceId = cancelItemFlowAllRouteDto.getInstanceId();
        List<MetaClassInstance> informationFlowList = internalUmlService.fetchInstanceByIds(informationFlowIdList, projectId);
        List<ItemFlowRouteVo> itemFlowRouteVoList = new ArrayList<>();
        List<ModelPropertyInfo> informationFlowModels = modelPropertyInfoService.createModelPropertyInfoList(projectId,
                informationFlowList,
                Stream.of(UMLDefinitionConstants.InformationFlow_informationSource,
                        UMLDefinitionConstants.InformationFlow_informationTarget).collect(Collectors.toList()));
        informationFlowModels.forEach(model -> {
            List<MetaClassInstance> informationSource = model.queryListInstanceValue(UMLDefinitionConstants.InformationFlow_informationSource);
            List<MetaClassInstance> informationTarget = model.queryListInstanceValue(UMLDefinitionConstants.InformationFlow_informationTarget);
            ItemFlowRouteVo itemFlowRouteVo = new ItemFlowRouteVo();
            List<String> allRealizingRoute = new ArrayList<>(findAllRealizing(projectId, instanceId, informationSource.get(0).getId(), informationTarget.get(0).getId()));
            allRealizingRoute.add(instanceId);
            itemFlowRouteVo.setItemFlowRoute(allRealizingRoute);
            itemFlowRouteVo.setItemFlowId(model.getInstanceId());
            itemFlowRouteVoList.add(itemFlowRouteVo);
        });
        return itemFlowRouteVoList;
    }

    @NotNull
    public ModelResultVo updateItemFlowFromAndToActivity(UpdateItemFlowFromAndToActivityDTO updateItemFlowFromAndToActivityDTO) {
        LogUtil.printSerializeOnlineLogs("updateItemFlowFromAndToActivityDTO: ", updateItemFlowFromAndToActivityDTO);
        final String projectId = updateItemFlowFromAndToActivityDTO.getProjectId();
        final MetaClassInstance itemFlow = internalUmlService.fetchInstance(updateItemFlowFromAndToActivityDTO.getInstanceId(), projectId);
        ModelResultVo modelResultVo = new ModelResultVo();
        if (Objects.isNull(itemFlow)) {
            log.error("项流id{}模型不存在", updateItemFlowFromAndToActivityDTO.getInstanceId());
            throw AbortExecutionException.build(ErrorCode.MODEL_NO_EXIST);
        }

        LocalTransaction transaction = transactionService.createTransaction(projectId, UPDATE_MODEL);
        try {
            List<MetaClassInstance> relatedActivityEdgeList = singleUpdateActivityGroupProperty(
                    projectId, itemFlow, updateItemFlowFromAndToActivityDTO.getFromToActivityGroup());
            transactionService.commit(projectId);
            InstanceVoUtils.fillModelResultVo(modelResultVo, transaction);
            modelResultVo.getModifyModel().addAll(relatedActivityEdgeList.stream().map(BasicRElement::getId).collect(Collectors.toList()));
        } catch (TransactionNotExistingException | LocalTransactionNotStartException e) {
            throw AbortExecutionException.build(ErrorCode.TRANSACTION_ERROR, e);
        } catch (Exception e) {
            transactionService.rollBack(projectId, transaction);
            throw AbortExecutionException.build(ErrorCode.SERVICE_ERROR, e);
        }

        return modelResultVo;
    }

    /**
     * desciption:查询与当前边两端直接匹配的实现项流
     */
    @NotNull
    public List<CurrentRrealizedItemFlowVo> queryCurrentRealizedItemFlow(String projectId, String instanceId) {
        LogUtil.printOnlineLogs("queryCurrentRealizedItemFlow -> projectId: {}, instanceId: {}", projectId, instanceId);
        MetaClassInstance relationship = internalUmlService.fetchInstance(instanceId, projectId);
        if (Objects.isNull(relationship)) {
            log.error("关系模型查找失败");
            throw AbortExecutionException.build(ErrorCode.MODEL_NO_EXIST);
        }
        ModelPropertyInfo relationshipPropertyInfo = modelPropertyInfoService.createSimpleModelPropertyInfo(projectId, relationship,
                Stream.of(UMLDefinitionConstants.A_realization_abstraction_flow_abstraction,
                        UMLDefinitionConstants.A_realizingConnector_informationFlow_informationFlow,
                        UMLDefinitionConstants.A_realizingActivityEdge_informationFlow_informationFlow,
                        UMLDefinitionConstants.A_realizingMessage_informationFlow_informationFlow).collect(Collectors.toList()));
        List<MetaClassInstance> realizationItemFlow = relationshipPropertyInfo.queryListInstanceValue(
                UMLDefinitionConstants.A_realization_abstraction_flow_abstraction);
        List<MetaClassInstance> realizingConnectorItemFlow = relationshipPropertyInfo.queryListInstanceValue(
                UMLDefinitionConstants.A_realizingConnector_informationFlow_informationFlow);
        List<MetaClassInstance> realizingActivityEdgeItemFlow = relationshipPropertyInfo.queryListInstanceValue(
                UMLDefinitionConstants.A_realizingActivityEdge_informationFlow_informationFlow);
        List<MetaClassInstance> realizingMessageItemFlow = relationshipPropertyInfo.queryListInstanceValue(
                UMLDefinitionConstants.A_realizingMessage_informationFlow_informationFlow);
        List<MetaClassInstance> currentItemFlows = Stream.of(realizationItemFlow, realizingConnectorItemFlow,
                realizingActivityEdgeItemFlow, realizingMessageItemFlow).flatMap(Collection::stream).collect(Collectors.toList());
        Map<String, ModelPropertyInfo> itemFlowPropertyInfo = modelPropertyInfoService.createModelPropertyInfoMap(projectId, currentItemFlows,
                Stream.of(UMLDefinitionConstants.InformationFlow_informationSource,
                        UMLDefinitionConstants.InformationFlow_informationTarget).collect(Collectors.toList()));
        // itemFlow/source/target添加至allInstances,批量查询Name
        List<MetaClassInstance> allInstances = new ArrayList<>();
        itemFlowPropertyInfo.forEach((key, value) -> {
            allInstances.add(value.getInstance());
            allInstances.addAll(value.queryListInstanceValue(UMLDefinitionConstants.InformationFlow_informationSource));
            allInstances.addAll(value.queryListInstanceValue(UMLDefinitionConstants.InformationFlow_informationTarget));
        });

        Map<String, ModelPropertyInfo> allInstancesInfoMap = modelPropertyInfoService.createModelPropertyInfoMap(
                projectId, allInstances, Stream.of(UMLDefinitionConstants.NamedElement_name).collect(Collectors.toList()));
        return currentItemFlows.stream().map(it -> {
            CurrentRrealizedItemFlowVo currentRrealizedItemFlowVo = new CurrentRrealizedItemFlowVo();
            ModelPropertyInfo informationFlowPropertyInfo = itemFlowPropertyInfo.get(it.getId());
            List<MetaClassInstance> sourceList = informationFlowPropertyInfo.queryListInstanceValue(UMLDefinitionConstants.InformationFlow_informationSource);
            List<MetaClassInstance> targetList = informationFlowPropertyInfo.queryListInstanceValue(UMLDefinitionConstants.InformationFlow_informationTarget);
            if (CollectionUtils.isEmpty(sourceList) || CollectionUtils.isEmpty(targetList)) {
                log.error("关系两端有一端不存在");
                throw AbortExecutionException.build(ErrorCode.MODEL_NO_EXIST);
            }
            MetaClassInstance source = sourceList.get(0);
            MetaClassInstance target = targetList.get(0);

            Map<MetaClassInstance, SelectElementItem> selectElementItemMap = fillItemFlowInfoByBatch(
                    Stream.of(it, source, target).collect(Collectors.toList()), allInstancesInfoMap, Collections.emptyMap());
            SelectElementItem itemFlowInfo = selectElementItemMap.get(it);
            SelectElementItem sourceInfo = selectElementItemMap.get(source);
            SelectElementItem targetInfo = selectElementItemMap.get(target);
            currentRrealizedItemFlowVo.setItemFlowId(itemFlowInfo.getInstanceId());
            currentRrealizedItemFlowVo.setItemFlowName(itemFlowInfo.getName());
            currentRrealizedItemFlowVo.setSourceId(sourceInfo.getInstanceId());
            currentRrealizedItemFlowVo.setSourceName(sourceInfo.getName());
            currentRrealizedItemFlowVo.setTargetId(targetInfo.getInstanceId());
            currentRrealizedItemFlowVo.setTargetName(targetInfo.getName());
            return currentRrealizedItemFlowVo;
        }).collect(Collectors.toList());
    }

    @NotNull
    public ItemFlowEndListVo queryItemFlowEnds(String projectId, String instanceId) {
        LogUtil.printOnlineLogs("queryItemFlowEnds -> projectId: {}, instanceId: {}", projectId, instanceId);
        return internalItemFlowService.queryItemFlowEnds(projectId, instanceId);
    }

    @NotNull
    public ModelResultVo realizeAllItemFlow(@NotNull RealizeAllItemFLowDTO realizeAllItemFLowDTO) {
        LogUtil.printSerializeOnlineLogs("realizeAllItemFLowDTO: ", realizeAllItemFLowDTO);
        final ModelResultVo modelResultVo = new ModelResultVo();
        final String projectId = realizeAllItemFLowDTO.getProjectId();
        final String instanceId = realizeAllItemFLowDTO.getInstanceId();

        // 如果不存在为未实现项流，则直接返回
        List<ItemFlowRouteVo> itemFlowRouteVos = queryActivityEdgeItemFlowAllRoute(projectId, instanceId);
        if (CollectionUtils.isEmpty(itemFlowRouteVos)) {
            return modelResultVo;
        }
        LocalTransaction transaction = transactionService.createTransaction(
                projectId, ModelActionName.UPDATE_PROPERTY);
        try {
            List<String> unrealizedItemFlowIds = itemFlowRouteVos.stream().map(ItemFlowRouteVo::getItemFlowId).collect(Collectors.toList());
            List<String> allItemFlowRouteIds = itemFlowRouteVos.stream().flatMap(it -> it.getItemFlowRoute().stream()).collect(Collectors.toList());
            Map<String, MetaClassInstance> instanceMap = internalUmlService.fetchInstances(
                    Stream.concat(unrealizedItemFlowIds.stream(), allItemFlowRouteIds.stream()).collect(Collectors.toList()), projectId);
            // 1.批量查询承载模型的实现属性，如果实现属性里包含路径，则不进行属性追加
            MofResultContainer mofResultContainer = internalUmlService.getMofResultContainer(projectId,
                    unrealizedItemFlowIds.stream().map(instanceMap::get).collect(Collectors.toList()),
                    Stream.of(UMLDefinitionConstants.InformationFlow_realization,
                            UMLDefinitionConstants.InformationFlow_realizingConnector,
                            UMLDefinitionConstants.InformationFlow_realizingActivityEdge,
                            UMLDefinitionConstants.InformationFlow_realizingMessage).collect(Collectors.toList()));
            List<AppendModelDTO> appendModelDTOS = new ArrayList<>();
            MetaClassInstance instance = internalUmlService.fetchExistInstance(instanceId, projectId);
            String propertyKey;
            if (internalUmlService.checkInstanceType(projectId, instance, UMLDefinitionConstants.Connector)) {
                propertyKey = UMLDefinitionConstants.InformationFlow_realizingConnector;
            } else if (internalUmlService.checkInstanceType(projectId, instance, UMLDefinitionConstants.Message)) {
                propertyKey = UMLDefinitionConstants.InformationFlow_realizingMessage;
            } else if (internalUmlService.checkInstanceType(projectId, instance, UMLDefinitionConstants.ActivityEdge)) {
                propertyKey = UMLDefinitionConstants.InformationFlow_realizingActivityEdge;
            } else {
                propertyKey = UMLDefinitionConstants.InformationFlow_realization;
            }
            itemFlowRouteVos.forEach(itemFlowRouteVo -> {
                final String itemFlowId = itemFlowRouteVo.getItemFlowId();
                List<String> itemFlowRoutes = itemFlowRouteVo.getItemFlowRoute();
                List<MetaClassInstance> realizedValues = mofResultContainer.queryListInstanceProperty(itemFlowId, propertyKey);
                List<String> realizedValueIds = realizedValues.stream().map(BasicRElement::getId).collect(Collectors.toList());
                itemFlowRoutes.removeAll(realizedValueIds);
                appendModelDTOS.add(new AppendModelDTO(projectId, itemFlowId, propertyKey,
                        itemFlowRoutes.stream().map(instanceMap::get).collect(Collectors.toList())));
            });
            umlService.appendModelByBatch(projectId, appendModelDTOS);
            transactionService.commit(projectId);
            InstanceVoUtils.fillModelResultVo(modelResultVo, transaction);
            modelResultVo.getModifyModel().addAll(allItemFlowRouteIds);
        } catch (TransactionNotExistingException | LocalTransactionNotStartException e) {
            throw AbortExecutionException.build(ErrorCode.TRANSACTION_ERROR, e);
        } catch (Exception e) {
            transactionService.rollBack(projectId, transaction);
            throw AbortExecutionException.build(ErrorCode.PROPERTY_UPDATE_ERROR, e);
        }
        return modelResultVo;
    }
}
